<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>主动发送消息</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <!--浏览器缩放-->
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <!--引入jssdk-->
  <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
  <!--引入网络工具-->
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <!--调试工具-->
  <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/vConsole/3.3.4/vconsole.min.js"></script>
  <!--hash1签名工具-->
  <script src="https://cdn.bootcdn.net/ajax/libs/jshashes/1.0.8/hashes.min.js"></script>
</head>
<body>
<script type="text/javascript">

  //接口地址
  let baseUrl = "http://192.168.0.101:9999/wechat/cgi-bin";
  //政务微信corpid
  let corpid = '***';

  //应用secret
  let corpsecret = '***';

  //应用id
  let agentid = ***;

  //console控制台
  let vConsole = new VConsole();

  //步骤
  //1、获取accessToken 需缓存
  //根据corpid和应用secret获取accessToken，需要缓存7000秒
  function getAccessToken() {
    return axios.get(baseUrl + '/gettoken', {
      params: {
        'corpid': corpid, 'corpsecret': corpsecret
      }
    });
  }

  //2、构造消息体
  //文本消息
  let textMessage = {
    "touser" : "18938890589",
    "msgtype" : "text",
    "agentid" : agentid,
    "text" : {
      "content" : "你的快递已到，请携带工卡前往邮件中心领取。<br>出发前可查看<a href=\"http://www.baidu.com\">邮件中心视频实况</a>，聪明避开排队。"
    }
  };
  //卡片消息
  let textCardMessage = {
    "touser" : "18938890589",
    "msgtype" : "textcard",
    "agentid" : agentid,
    "textcard" : {
      "title" : "领奖通知",
      "description" : "<div class=\"gray\">2016年9月26日</div> <div class=\"normal\">恭喜你抽中iPhone 7一台，领奖码：1234</div><div class=\"highlight\">请于2016年10月10日前联系行政同事领取</div>",
      "url" : "http://www.baidu.com"
    }
  }

  //3、发送消息
  async function sendMessage(msg) {
    let accessTokenResp = await getAccessToken();
    let accessToken = accessTokenResp.data.access_token;
    let resp = await axios.post(baseUrl + '/message/send?access_token=' + accessToken,msg);
    alert(resp.data.errmsg);
    console.log(resp.data);
  }
  //4、调用
  (function () {
    //发送文本消息
    sendMessage(textMessage);
    //发送卡片消息
    sendMessage(textCardMessage);
  })();
</script>
</body>
</html>
